package com.hhd.pdf.component.row;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.component.sort.PdfListSortor;
import com.hhd.pdf.variable.ParsedFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class IterableRowComponent extends RowComponent {
    @Autowired
    @Lazy
    PdfListSortor pdfListSortor;

    @Override
    protected void customAbleRender(PdfPTable table, int colNum, GeneratorContext context) {
        String listFormula = getListFormula(context);
        VariableContext variableContext = context.getRuntimeData().getVariableContext();
        List<VariableContext> subContexts = variableContext.subContextByFormula(ParsedFormula.formula(listFormula), false);
        subContexts = sortContext(context, subContexts, variableContext);
        if (CommonUtils.isEmpty(subContexts)) return;

        List<Element> cols = getCols(context);


        int count = 0;
        for (VariableContext subContext : subContexts) {
            for (Element col : cols) {
                GeneratorContext runtime = createSubGeneratorContext(context, subContext, col);

                List<com.itextpdf.text.Element> elements = genChildren(runtime, col);
                PdfPCell cell = getCell();
                if (!CommonUtils.isEmpty(elements)) {
                    elements.forEach(cell::addElement);
                    count++;
                }
                table.addCell(cell);
            }
        }

        fillTableCellColumns(table, colNum, count);
    }

    private GeneratorContext createSubGeneratorContext(GeneratorContext context, VariableContext subContext, Element col) {
        GeneratorContext runtime = context.runtime(col);
        runtime.getRuntimeData().setVariableContext(subContext);
        return runtime;
    }

    private List<VariableContext> sortContext(GeneratorContext context, List<VariableContext> subContext, VariableContext variableContext) {
        return pdfListSortor.sort(subContext, context.getParsingElement(), variableContext);
    }

    @Override
    protected boolean isCustomAbleRender(GeneratorContext context) {
        return !CommonUtils.isEmpty(getListFormula(context));
    }

    private String getListFormula(GeneratorContext context) {
        Element parsingElement = context.getParsingElement();
        String s = parsingElement.attributeValue("list");
        return s;
    }
}
